package org.algorithm.wE1.数组.三月.第二周;

import java.util.Arrays;

/**
 * @author wE1
 * @version 1.0
 * @date 2022/03/0 9:07 PM    星期一的作业
 * @description:
 * <p>
 *     数组中三数相加最接近target
 *     输入：nums = [-1,2,1,-4], target = 1
 *     输出：2
 *     解释：与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
 * </p>
 *
 * uri: https://leetcode-cn.com/problems/3sum-closest/solution/hua-jie-suan-fa-16-zui-jie-jin-de-san-shu-zhi-he-b/
 */
public class 最接近的三数之和 {

    public static void main(String[] args) {
       // [-3, 0, 1, 2]
        int[] nums = {-3, 0, 1, 2};
        System.out.println(threeSumClosest(nums, 1));
    }

    public static int threeSumClosest(int[] nums, int target) {
        if(nums == null || nums.length<3){
            return -1;
        }
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));
        int ans = nums[0]+nums[1]+nums[2];
        for (int i = 0; i <nums.length ; i++) {
            int left = i+1;
            int right = nums.length-1;
            while (left<right){
                int sum =  nums[i]+nums[left]+nums[right];
                if((Math.abs(target - sum) < Math.abs(target - ans))){
                    ans=sum;
                }
                if(target < sum){
                    right--;
                }else if(target > sum){
                    left++;
                }else {
                    return ans;
                }

            }
        }
        return ans;
    }
}
